﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore2210A.Domain;

namespace WorkflowCore2210A.Application.Steps
{
    public class AuditStep : StepBody
    {
        private readonly IWorkflowService _workflowService;
        private readonly WorkflowCoreContext _db;
        public AuditStep(IWorkflowService workflowService, WorkflowCoreContext db)
        {
            _workflowService = workflowService;
            _db = db;
        }

        public long AuditUserId { get; set; } // 从WorkflowDefinitionModel中的步骤节点中传递过来
        public string AuditUserName { get; set; }
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            // 如果当前执行节点没有审批，则创建创建一个审批事件
            if (!context.ExecutionPointer.EventPublished)
            {
                // 添加待审批
                _workflowService.AddAudit(new()
                {
                    AuditUserId = AuditUserId,
                    AuditUserName = AuditUserName, // 当前待审批人
                    ExecutionPointerId = context.ExecutionPointer.Id, // 当前执行节点
                    StepId = context.Step.ExternalId, // 前端传递过来的步骤ID，  如：first,second
                    StepName = context.Step.Name,     // 前端传递过来的步骤名称，如：主管,经理等
                    WorkflowId = context.Workflow.Id, // 工作流实例ID
                });

                // 修改流程实例
                var workflowInstance = _db.WorkflowInstance.FirstOrDefault(x => x.WorkflowId == context.Workflow.Id);
                workflowInstance.StepName = context.Step.Name;
                workflowInstance.AuditUserName = AuditUserName;
                _db.SaveChanges();


                Console.WriteLine($"等待{AuditUserName}审批。。。");
                // 这里第二个参数，以后要进行调整，如果使用context.Workflow.Id会出现一个问题：
                // 在多人审批时，若其中一人审批，会将其他人的等待审批事件取消掉。
                // 解决办法：EventKey 最终解决办法，换成：Guid.NewGuid()
                return ExecutionResult.WaitForEvent("MyEvent", context.Workflow.Id, DateTime.Now);
            }

            // 获取审批意见
            var eventData = context.ExecutionPointer.EventData;
            Console.WriteLine($"用户{AuditUserName}审批意见是：{eventData}");

            return ExecutionResult.Next();
        }
    }
}
